﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using LY.Business.ServiceImpl;
using LY.Common;
using LY.Interface;
using System.Configuration;
using LY.Entity;

namespace QJ.CMS.tools
{
    /// <summary>
    /// admin_ajax 的摘要说明
    /// </summary>
    public class AdminAjax : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            //取得处事类型
            string action = RBSRequest.GetQueryString("action");
            switch (action)
            {

                case "sms_message_post": //发送手机短信
                    sms_message_post(context);
                    break;
                case "get_validate_code": //手机验证码
                    string sign = RBSRequest.GetQueryString("sign");
                    get_validate_code(context, sign);
                    break;
                case "validate_phone": //验证手机
                    validate_phone(context);
                    break;
                case "validate_user": //验证用户名
                    string name = RBSRequest.GetQueryString("name");
                    validate_user(context, name);
                    break;

                case "validate_SESSION_SMS_CODE": //验证手机验证码
                    validate_SESSION_SMS_CODE(context);
                    break;

                //
                case "validate_BankBangDing": //验证银行卡
                    validate_BankBangDing(context);
                    break;


            }
        }

        /// <summary>
        /// 验证银行卡
        /// </summary>
        /// <param name="context"></param>
        private void validate_BankBangDing(HttpContext context)
        {

            //string memberId = RBSRequest.GetQueryString("memberId");
            string cardNo = RBSRequest.GetString("param");
            if (string.IsNullOrEmpty(cardNo))
            {
                context.Response.Write("{ \"info\":\"请输入银行卡\", \"status\":\"n\" }");
                return;
            }
            IMemberService memberService = new MemberService();
            if (memberService.CheckBankCardDangDing(45, cardNo) == "yes")
            {
                context.Response.Write("{ \"info\":\"银行卡已被绑定，请更换！\", \"status\":\"n\" }");
                return;
            }
            context.Response.Write("{ \"info\":\"银行卡可用\", \"status\":\"y\" }");
            return;

        }

        private void validate_SESSION_SMS_CODE(HttpContext context)
        {
            var code = RBSRequest.GetString("param");
            if (context.Session[RBSKeys.SESSION_SMS_CODE] == null)
            {
                context.Response.Write("{ \"info\":\"请点击获取验证码!\", \"status\":\"n\" }");
                return;
            }
            else
            {
                //如果图形验证码不正确则返回//输入验证码超过3次，此次验证码失效，重新获取
                if (code.ToLower() != context.Session[RBSKeys.SESSION_SMS_CODE].ToString().ToLower())
                {
                    if (context.Session["AdminSumbitSun"] == null)
                    {
                        context.Session["AdminSumbitSun"] = 1;
                    }
                    else
                    {
                        context.Session["AdminSumbitSun"] = Convert.ToInt32(context.Session["AdminSumbitSun"]) + 1;
                    }
                    //判断输入错误次数
                    if (context.Session["AdminSumbitSun"] != null && Convert.ToInt32(context.Session["AdminSumbitSun"]) > 2)
                    {
                        context.Response.Write("{ \"info\":\"验证码已失效,请重新获取!\", \"status\":\"n\" }");
                        context.Session[RBSKeys.SESSION_SMS_CODE] = null;
                    }
                    else
                    {
                        context.Response.Write("{ \"info\":\"手机验证码错误,请重新输入验证码!\", \"status\":\"n\" }");
                    }
                    return;
                }
                else
                {
                    //判断输入错误次数
                    if (context.Session["AdminSumbitSun"] != null && Convert.ToInt32(context.Session["AdminSumbitSun"]) > 5)
                    {
                        context.Response.Write("{ \"info\":\"验证码已失效,请重新获取!\", \"status\":\"n\" }");
                        context.Session[RBSKeys.SESSION_SMS_CODE] = null;
                    }
                    else
                    {
                        context.Session["AdminSumbitSun"] = null;
                        context.Response.Write("{ \"info\":\"手机验证码正确!\", \"status\":\"y\" }");
                    }
                    return;
                }
            }
        }

        private void validate_phone(HttpContext context)
        {
            string phpone = RBSRequest.GetString("param");
            context.Session[RBSKeys.SESSION_SMS_CODE] = null;
            if (string.IsNullOrEmpty(phpone))
            {
                context.Response.Write("{ \"info\":\"请输入正确的手机号码\", \"status\":\"n\" }");
                return;
            }
            IMemberService memberService = new MemberService();
            if (memberService.ExistsPhone(phpone))
            {
                context.Response.Write("{ \"info\":\"手机号码已被绑定，请更换！\", \"status\":\"f\" }");
                return;
            }
            context.Response.Write("{ \"info\":\"手机号码可用\", \"status\":\"y\" }");
            return;
        }
        private void validate_user(HttpContext context, string name)
        {
            string phpone = RBSRequest.GetString("param");
            context.Session[RBSKeys.SESSION_SMS_CODE] = null;
            if (string.IsNullOrEmpty(phpone))
            {
                context.Response.Write("{ \"info\":\"请输入用户名\", \"status\":\"n\" }");
                return;
            }
            IMemberService memberService = new MemberService();
            if (memberService.GetMemberInfoByName(phpone) != null)
            {
                if (name == "")
                {
                    context.Response.Write("{ \"info\":\"用户名已被注册，请更换！\", \"status\":\"n\" }");
                    return;
                }
                if (name.Trim() == memberService.GetMemberInfoByName(phpone).Nickname.Trim())
                {
                    context.Response.Write("{ \"info\":\"用户名可用\", \"status\":\"y\" }");
                }
                else
                {
                    context.Response.Write("{ \"info\":\"用户名已被注册，请更换！\", \"status\":\"n\" }");
                }
                return;
            }
            context.Response.Write("{ \"info\":\"用户名可用\", \"status\":\"y\" }");
            return;
        }

        private void get_validate_code(HttpContext context, string sign)
        {
            var phone = RBSRequest.GetQueryString("phone");
            if (string.IsNullOrEmpty(phone))
            {
                context.Response.Write("{ \"info\":\"请输入手机号码！\", \"status\":\"n\" }");
                context.Response.End();
            }
            //加限制每个号码 每天最多发{0}条短信 IP
            string ip = LY.Common.Utils.Tools.GetUserIp();
            //每个手机短信发送次数
            int count = ConfigurationManager.AppSettings["PhoneCodeCount"] == null ? 10 : int.Parse(ConfigurationManager.AppSettings["PhoneCodeCount"]);

            ISysTemplateService _templateService = new SysTemplateService();
            //返回次数
            int retcount = _templateService.GetCodeCount(phone, ip);
            if (retcount >= count)
            {
                //超过今日发送次数
                context.Response.Write("{ \"info\":\"您的号码已超过单日最大接收数量，请联系客服人员！\", \"status\":\"n\" }");
                context.Response.End();
            }



            var templateModel = _templateService.GetSysTemplate(sign);
            //：{code}，{valid}
            //重新赋值
            context.Session[RBSKeys.SESSION_SMS_CODE] = Utility.Number(6);

            string smstemp = templateModel.TemplateContent;
            smstemp = smstemp.Replace("{code}", context.Session[RBSKeys.SESSION_SMS_CODE].ToString());
            smstemp = smstemp.Replace("{valid}", "3");

            var msg = string.Empty;
            //发送验证码   
            var flag = SmsMessage.Send(phone, smstemp, 1, out msg);
            if (flag)
            {
                T_Code code = new T_Code()
                {
                    Code = context.Session[RBSKeys.SESSION_SMS_CODE].ToString(),
                    Tel = phone,
                    UserIp = ip,
                    CreateDate = DateTime.Now,
                    Type = 1//1 注册验证码
                };
                _templateService.AddCodeCount(code);
                context.Response.Write("{ \"info\":\"短信发送成功,请注意查收!\", \"status\":\"y\" }");
            }
            else
                context.Response.Write("{ \"info\":\"短信发送失败," + msg + "!\", \"status\":\"n\" }");
        }

        private void sms_message_post(HttpContext context)
        {
            throw new NotImplementedException();
        }



        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}